#!/bin/bash
mydir=`dirname "$0"`
uninstallToolPath="$mydir/UninstallerTool"
installBasePath="${2}"
installSubPath="."
payloadFile="${PACKAGE_PATH}/../../Resources/Payloads/RGLink.app.5175016f.pax.gz"
productName="(null)"
productNumber="112"
newLocation="/Applications/Red Giant Link.app"
tmpLocation="${INSTALLER_TEMP}/$(basename -s.pax.gz ${payloadFile})"
if [ -d "${tmpLocation}" ]; then
    echo "Moving Link app at ${tmpLocation} back to ${newLocation}"
    if [ -d "${newLocation}" ]; then
        echo "Link exists at ${newLocation}; removing ..."
        rm -rf "${newLocation}"
    fi
    mv -v "${tmpLocation}" "${newLocation}"
fi
for oldLinkFolder in "/Applications/Red Giant Link" "/Applications/Red Giant"; do
    oldLocation="${oldLinkFolder}/Red Giant Link.app"
    if [ -d "${oldLocation}" ]; then
        if [ -d "${newLocation}" ]; then
            oldLocationVersion=$(/usr/libexec/PlistBuddy "${oldLocation}/Contents/Info.plist" -c "Print :CFBundleVersion")
            oldLocationRC=$?
            newLocationVersion=$(/usr/libexec/PlistBuddy "${newLocation}/Contents/Info.plist" -c "Print :CFBundleVersion")
            newLocationRC=$?
            if [[ ${oldLocationRC} != 0 ]]; then
                /bin/rm -rf "${oldLocation}"
            elif [[ ${newLocationRC} != 0 || "z${newLocationVersion}" < "z${oldLocationVersion}" ]]; then
                /bin/rm -rf "${newLocation}"
                /bin/mv "${oldLocation}" "${newLocation}"
            else
                /bin/rm -rf "${oldLocation}"
            fi
        else
            /bin/mv "${oldLocation}" "${newLocation}"
        fi
    fi
    if [ -d "${oldLinkFolder}" ]; then
        /bin/rm -rf "${oldLinkFolder}"
    fi
done
installingVersion='1.9.11.2'
existingVersion=$(/usr/libexec/PlistBuddy "$2/${installSubPath}/Red Giant Link.app/Contents/Info.plist" -c "Print :CFBundleVersion")
rc=$?
if [[ $rc != 0 || "z${existingVersion}" < "z${installingVersion}" ]]; then
    /bin/rm -rf "${newLocation}"
    /usr/bin/xattr -d com.apple.quarantine "${payloadFile}"
    /bin/mkdir -p "$2/${installSubPath}"
    pushd "$2/${installSubPath}"
    /bin/pax -rzf "${payloadFile}"
    popd
fi
